﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFromTools
{
    public partial class DownloadForm : Form
    {
        public DownloadForm()
        {
            InitializeComponent();
        }

        private  void btnDownload_Click(object sender, EventArgs e)
        {
            var files = GetDownloadingFiles(txtHtml.Text);
            foreach (var file in files)
            {
                using (WebClient wc = new WebClient())
                {
                    // 我们尝试去下载文件
                    Uri fileUri = new Uri(new Uri(txtUrl.Text), file.Url);

                    try
                    {
                        //Task task = wc.DownloadFileTaskAsync(fileUri, file.Filename);
                        // 可以在这里执行代码。
                        //await task;
                        wc.DownloadFile(fileUri, file.Filename);

                        txtResult.AppendText(file.Filename);  
                    }
                    catch(Exception exp)
                    {
                        txtResult.AppendText(exp.Message);
                        txtResult.AppendText(fileUri.ToString());
                    }
                    txtResult.AppendText(Environment.NewLine);
                }
            }
            txtResult.AppendText("下载完成。");
            //string achorPattern = @"(?<=<a [^>]+?>)[\s\S]*?(?=</a>)";
            //string achorHref = @"(?<=href=[""']?)[\s\S]*?(?=[""']?[ |^>])";
            //HashSet<String> urls = new HashSet<string>();

            //Regex reg = new Regex(@"(?is)<a[^>]*?href=(['""\s]?)(?<href>[^'""\s]*)\1[^>]*?>[\s\S]*?(?=</a>)");
            //MatchCollection match2 = reg.Matches(txtHtml.Text);
            //foreach (Match m in match2)
            //{
            //    txtResult.Text += m.Groups["href"].Value;
            //}

            ////MatchCollection mc = Regex.Matches(txtHtml.Text, @"<a\s+href=(?<url>.+?)>(?<content>.+?)</a>");
            //MatchCollection mc = Regex.Matches(txtHtml.Text, @"<a\s+href=(?<url>.+?)><[^>]+?>(?<content>.+?)</[^>]+?></a>");
            //foreach (Match m in mc)
            //{
            //    //url = m.Groups["url"].Value;

            //    //content = m.Groups["content"].Value;
            //}


            //MatchCollection urlMatches = GetMatches(achorPattern, txtHtml.Text);
            //foreach (Match match in urlMatches)
            //{
            //    string subTitle = GetFirstMatch(achorPattern, match.Value.Trim());
            //    if (subTitle == null)
            //        continue;
            //    string href = GetFirstMatch(achorHref, match.Value.Trim());
            //    if (href == null)
            //        continue;
            //    href = href.Trim('"', '/', '\'');
            //    urls.Add(href);
            //}

            //HttpClient _httpClient = new HttpClient();
            //foreach (var url in urls)
            //{
            //    //_httpClient.GetStreamAsync client.DownloadFile("http://something", @"D:\Downloads\1.zip");
            //}


            //using (WebClient wc = new WebClient())
            //{
            //    // 我们尝试去下载 python 的安装包。
            //    Task task = wc.DownloadFileTaskAsync("https://www.python.org/ftp/python/3.5.2/python-3.5.2-amd64.exe", "python.exe");
            //    // 可以在这里执行代码。
            //    await task;
            //}
            //txtResult.Text = "下载完成。";

            //foreach (var url in urls)
            //{
            //    using (var client = new WebClient())
            //    {
            //        client.DownloadFile("http://something", @"D:\Downloads\1.zip");
            //    }
            //}
        }

        private static string GetFirstMatch(string pattern, string originalText)
        {
            MatchCollection matches = GetMatches(pattern, originalText);
            if (matches.Count > 0)
            {
                return matches[0].Value;
            }
            else
            {
                return null;
            }
        }

        private static MatchCollection GetMatches(string pattern, string originalText)
        {
            Regex tmpRegex = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matches = tmpRegex.Matches(originalText);

            return matches;
        }

        private static IList<DownloadingFile> GetDownloadingFiles(string html)
        {
            // string pattern, 
            var files = new List<DownloadingFile>();
            MatchCollection mc = Regex.Matches(html, @"<a\s+href=(?<url>.+?)><[^>]+?>(?<content>.+?)</[^>]+?></a>");
            foreach (Match m in mc)
            {
                files.Add(new DownloadingFile { Url = m.Groups["url"].Value.Trim('"', ' '), Filename = m.Groups["content"].Value.Trim('"', ' ') });
            }
            return files;
        }
    }

    public partial class DownloadingFile
    {
        public string Url { get; set; }
        public string Filename { get; set; }
    }
}
